<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="kYQuniuaRZuL9fq0DATfL7extAwcqWG6Ki286ZMcpak">
  <meta name="baidu-site-verification" content="code-MRqS7DOO9x">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha256-DfWjNxDkM94fVBWx1H5BMMp0Zq7luBlV8QRcSES7s+0=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blogwxb.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.11.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":true,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":null,"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="jquery ajax对原生XHR的封装。 优点  无页面刷新 异步 支持JSONP 为以后的优秀的http请求库打下来基础">
<meta property="og:type" content="article">
<meta property="og:title" content="jquery中的ajax、fetch和axios的区别">
<meta property="og:url" content="https://blogwxb.cn/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/index.html">
<meta property="og:site_name" content="会飞的猪9527">
<meta property="og:description" content="jquery ajax对原生XHR的封装。 优点  无页面刷新 异步 支持JSONP 为以后的优秀的http请求库打下来基础">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blogwxb.cn/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/1.png">
<meta property="og:image" content="https://blogwxb.cn/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/2.png">
<meta property="article:published_time" content="2020-12-18T02:18:34.000Z">
<meta property="article:modified_time" content="2022-10-07T15:14:03.002Z">
<meta property="article:author" content="wxb">
<meta property="article:tag" content="Javescript">
<meta property="article:tag" content="HTML5">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blogwxb.cn/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/1.png">


<link rel="canonical" href="https://blogwxb.cn/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://blogwxb.cn/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/","path":"jquery中的ajax、fetch和axios的区别/","title":"jquery中的ajax、fetch和axios的区别"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>jquery中的ajax、fetch和axios的区别 | 会飞的猪9527</title>
  





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <!-- Google Analytics -->
  <script>
  window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
  ga('create', 'UA-XXXXX-Y', 'auto');
  ga('send', 'pageview');
  </script>
  <script async src='https://www.google-analytics.com/analytics.js'></script>
  <!-- End Google Analytics -->

  <!-- Baidu Analytics -->
  <script async src = 'https://zz.bdstatic.com/linksubmit/push.js'></script>
  <!-- End Baidu Analytics -->

<link rel="alternate" href="/atom.xml" title="会飞的猪9527" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">会飞的猪9527</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">32</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">5</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">91</span></a></li><li class="menu-item menu-item-commonweal"><a href="/404" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#jquery-ajax"><span class="nav-number">1.</span> <span class="nav-text">jquery ajax</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#fetch"><span class="nav-number">2.</span> <span class="nav-text">fetch</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#axios"><span class="nav-number">3.</span> <span class="nav-text">axios</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#axios%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="nav-number">3.1.</span> <span class="nav-text">axios拦截器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%80%E3%80%81-%E6%8B%A6%E6%88%AA%E5%99%A8%E6%B5%81%E7%A8%8B%E5%9B%BE"><span class="nav-number">3.1.1.</span> <span class="nav-text">一、 拦截器流程图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E6%8B%A6%E6%88%AA%E5%99%A8%E7%9A%84%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-number">3.1.2.</span> <span class="nav-text">二、拦截器的应用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E6%8B%A6%E6%88%AA%E5%99%A8%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">3.1.3.</span> <span class="nav-text">三、拦截器的使用</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="wxb"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">wxb</p>
  <div class="site-description" itemprop="description">主要是分享自己在Web前端的一些入的坑，脱的坑的经历，也会是分享一些Node后端的知识。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">91</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/dearDreamWeb" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;dearDreamWeb" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll site-overview-item animated">
    <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
      推荐
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.ruanyifeng.com/blog/" title="https:&#x2F;&#x2F;www.ruanyifeng.com&#x2F;blog&#x2F;" rel="noopener" target="_blank">阮一峰的网络日志</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://nav.blogwxb.cn/" title="https:&#x2F;&#x2F;nav.blogwxb.cn&#x2F;" rel="noopener" target="_blank">轩辕导航</a>
        </li>
    </ul>
  </div>

        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/dearDreamWeb" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://blogwxb.cn/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="wxb">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="会飞的猪9527">
      <meta itemprop="description" content="主要是分享自己在Web前端的一些入的坑，脱的坑的经历，也会是分享一些Node后端的知识。">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="jquery中的ajax、fetch和axios的区别 | 会飞的猪9527">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          jquery中的ajax、fetch和axios的区别
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-12-18 10:18:34" itemprop="dateCreated datePublished" datetime="2020-12-18T10:18:34+08:00">2020-12-18</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2022-10-07 23:14:03" itemprop="dateModified" datetime="2022-10-07T23:14:03+08:00">2022-10-07</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <!-- <span id="busuanzi_value_page_pv"></span> -->
      <span id="views_text"></span>
    </span>
</div>


        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="jquery-ajax"><a href="#jquery-ajax" class="headerlink" title="jquery ajax"></a>jquery ajax</h1><p>对原生XHR的封装。</p>
<p>优点</p>
<ul>
<li>无页面刷新</li>
<li>异步</li>
<li>支持JSONP</li>
<li>为以后的优秀的http请求库打下来基础<span id="more"></span>
缺点</li>
<li>本身是针对MVC的,不符合现在前端MVVM的模式</li>
<li>会造成回调地狱</li>
</ul>
<h1 id="fetch"><a href="#fetch" class="headerlink" title="fetch"></a>fetch</h1><p>Fetch 提供了一个更理想的替代方案，可以很容易地被其他技术使用，例如  <code>Service Workers</code>。是基于Promise设计的，可以搭配上async&#x2F;await使用。<br>关于service worker的一篇文章的介绍 <a target="_blank" rel="noopener" href="https://www.jianshu.com/p/1bc5bf8be43d">Service Workers简介</a>。</p>
<p>兼容性如下</p>
<p><img data-src="/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/1.png" alt="fetch兼容性"></p>
<p>优点：</p>
<ul>
<li>符合MVVM模式，脱离了XHR，是ES规范里新的实现方式</li>
<li>基于标准的Promise实现，支持async&#x2F;await</li>
<li>更加底层，提供的API丰富（request, response）</li>
<li>可以取消发送请求</li>
</ul>
<p>缺点：</p>
<ul>
<li>fetch不支持abort，不支持超时控制，使用setTimeout及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行，造成了流量的浪费</li>
<li>不支持JSONP</li>
<li>fetch只对网络请求报错，对400，500都当做成功的请求，需要封装去处理</li>
<li>fetch默认不会带cookie，需要添加配置项</li>
<li>fetch没有办法原生监测请求的进度，而XHR可以</li>
</ul>
<h1 id="axios"><a href="#axios" class="headerlink" title="axios"></a>axios</h1><p>Axios本质上也是对原生XHR的封装，只不过它是Promise的实现版本，符合最新的ES规范。</p>
<p>优点：</p>
<ul>
<li>浏览器和node.js都能用</li>
<li>支持 Promise API</li>
<li>客户端支持防止CSRF</li>
<li>提供了拦截器</li>
<li>可以取消发送请求</li>
<li>提供了一些并发请求的接口（重要，方便了很多的操作）</li>
</ul>
<p>缺点：</p>
<ul>
<li>采用的是XHR方式，所以输入、输出和用事件来跟踪的状态混杂在一个对象里</li>
</ul>
<p><strong>客户端支持防止CSRF的实现方式：</strong><br>每个请求都带一个从<code>cookie</code>中拿到的<code>key</code>, 根据浏览器<code>同源策略</code>，假冒的网站是<code>拿不到你cookie中的key</code>，这样，后台就可以轻松辨别出这个请求是否是用户在假冒网站上的误导输入，从而采取正确的策略。</p>
<h2 id="axios拦截器"><a href="#axios拦截器" class="headerlink" title="axios拦截器"></a>axios拦截器</h2><h3 id="一、-拦截器流程图"><a href="#一、-拦截器流程图" class="headerlink" title="一、 拦截器流程图"></a>一、 拦截器流程图</h3><p><img data-src="/jquery%E4%B8%AD%E7%9A%84ajax%E3%80%81fetch%E5%92%8Caxios%E7%9A%84%E5%8C%BA%E5%88%AB/2.png" alt="拦截器流程图"></p>
<h3 id="二、拦截器的应用场景"><a href="#二、拦截器的应用场景" class="headerlink" title="二、拦截器的应用场景"></a>二、拦截器的应用场景</h3><p>对请求和其响应进行特定的处理的时候。</p>
<ol>
<li>每个请求都附带后端返回的<code>token</code>，可以使用 <code>axios request 拦截器</code>，在这里，我们给每个请求都加 token,这样就可以节省每个请求再一次次的复制粘贴代码。</li>
<li>当token失效或者后端返回错误信息，都可以用 <code>axios response 拦截器</code>，我们统一处理所有请求成功之后响应过来的数据，然后对特殊数据进行处理，其他的正常分发。</li>
</ol>
<h3 id="三、拦截器的使用"><a href="#三、拦截器的使用" class="headerlink" title="三、拦截器的使用"></a>三、拦截器的使用</h3><p>主要用的方法：</p>
<ol>
<li><p>实例化axios<br>axios.create([config])<br>简单的例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> instance = axios.<span class="title function_">create</span>(&#123;</span><br><span class="line">  <span class="attr">baseURL</span>: <span class="string">&#x27;https://some-domain.com/api/&#x27;</span>,    <span class="comment">// 发送请求的前置的url</span></span><br><span class="line">  <span class="attr">timeout</span>: <span class="number">10000</span>,                              <span class="comment">// 请求超时的时间</span></span><br><span class="line">  <span class="attr">headers</span>: &#123;<span class="string">&#x27;X-Custom-Header&#x27;</span>: <span class="string">&#x27;foobar&#x27;</span>&#125;      <span class="comment">// 请求的headers</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></li>
<li><p>请求拦截器<br>axios.interceptors.request.use(function (config) {},function (error) {})<br>例子： </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 添加请求拦截器</span></span><br><span class="line">axios.<span class="property">interceptors</span>.<span class="property">request</span>.<span class="title function_">use</span>(<span class="keyword">function</span> (<span class="params">config</span>) &#123;</span><br><span class="line">    <span class="comment">// 在发送请求之前做些什么</span></span><br><span class="line">    <span class="keyword">return</span> config;</span><br><span class="line">  &#125;, <span class="keyword">function</span> (<span class="params">error</span>) &#123;</span><br><span class="line">    <span class="comment">// 对请求错误做些什么</span></span><br><span class="line">    <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">reject</span>(error);</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
</li>
<li><p>响应拦截器<br>axios.interceptors.response.use(function (config) {},function (error) {})<br>例子：  </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 添加响应拦截器</span></span><br><span class="line">axios.<span class="property">interceptors</span>.<span class="property">response</span>.<span class="title function_">use</span>(<span class="keyword">function</span> (<span class="params">response</span>) &#123;</span><br><span class="line">    <span class="comment">// 对响应数据做点什么</span></span><br><span class="line">    <span class="keyword">return</span> response;</span><br><span class="line">  &#125;, <span class="keyword">function</span> (<span class="params">error</span>) &#123;</span><br><span class="line">    <span class="comment">// 对响应错误做点什么</span></span><br><span class="line">    <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">reject</span>(error);</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
</li>
<li><p>移除拦截器</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> myInterceptor = axios.<span class="property">interceptors</span>.<span class="property">request</span>.<span class="title function_">use</span>(<span class="keyword">function</span> (<span class="params"></span>) &#123;<span class="comment">/*...*/</span>&#125;);</span><br><span class="line">axios.<span class="property">interceptors</span>.<span class="property">request</span>.<span class="title function_">eject</span>(myInterceptor);</span><br></pre></td></tr></table></figure></li>
</ol>
<p>注意：<br>请求拦截器和响应拦截器的两个回调函数参数，需要<code>有返回值</code>才能<code>继续</code>。  </p>
<ul>
<li>请求拦截器要返回回调函数的参数才行，否则请求将会被拦截，无法发送到后端，例子如下：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> $axios = axios.<span class="title function_">create</span>(&#123;</span><br><span class="line">    <span class="attr">timeout</span>: <span class="number">10000</span>,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 请求没法发送出去的情况</span></span><br><span class="line">$axios.<span class="property">interceptors</span>.<span class="property">request</span>.<span class="title function_">use</span>(<span class="function"><span class="params">config</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">&#125;, <span class="function"><span class="params">err</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(err))</span><br><span class="line"></span><br><span class="line">$axios.<span class="title function_">get</span>(<span class="string">&#x27;http://localhost:3030/api&#x27;</span>, &#123; <span class="attr">name</span>: <span class="string">&#x27;wxb&#x27;</span> &#125;).<span class="title function_">then</span>(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);   <span class="comment">// undefined， 请求也没有发送出去</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 请求发送出去的情况</span></span><br><span class="line">$axios.<span class="property">interceptors</span>.<span class="property">request</span>.<span class="title function_">use</span>(<span class="function"><span class="params">config</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> config;</span><br><span class="line">&#125;, <span class="function"><span class="params">err</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(err))</span><br><span class="line"></span><br><span class="line">$axios.<span class="title function_">get</span>(<span class="string">&#x27;http://localhost:3030/api&#x27;</span>, &#123; <span class="attr">name</span>: <span class="string">&#x27;wxb&#x27;</span> &#125;).<span class="title function_">then</span>(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);   <span class="comment">// &#123;config:&#123;xxx&#125;,data:&#123;xxx&#125;,headers:&#123;xxx&#125;,request:&#123;xxx&#125;,status:xxx,statusText:&#x27;xx&#x27;&#125;</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></li>
<li>响应拦截器返回什么数据，then就接收到什么数据</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> $axios = axios.<span class="title function_">create</span>(&#123;</span><br><span class="line">    <span class="attr">timeout</span>: <span class="number">10000</span>,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 例子1</span></span><br><span class="line">$axios.<span class="property">interceptors</span>.<span class="property">response</span>.<span class="title function_">use</span>(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;  </span><br><span class="line">&#125;, <span class="function"><span class="params">err</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(err))</span><br><span class="line"></span><br><span class="line">$axios.<span class="title function_">get</span>(<span class="string">&#x27;http://localhost:3030/api&#x27;</span>, &#123; <span class="attr">params</span>:&#123;<span class="attr">name</span>: <span class="string">&#x27;wxb&#x27;</span>&#125; &#125;).<span class="title function_">then</span>(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);  <span class="comment">// true</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 例子2</span></span><br><span class="line">$axios.<span class="property">interceptors</span>.<span class="property">response</span>.<span class="title function_">use</span>(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> res;  </span><br><span class="line">&#125;, <span class="function"><span class="params">err</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(err))</span><br><span class="line"></span><br><span class="line">$axios.<span class="title function_">get</span>(<span class="string">&#x27;http://localhost:3030/api&#x27;</span>, &#123; <span class="attr">params</span>:&#123;<span class="attr">name</span>: <span class="string">&#x27;wxb&#x27;</span>&#125; &#125;).<span class="title function_">then</span>(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);  <span class="comment">// &#123;config:&#123;xxx&#125;,data:&#123;xxx&#125;,headers:&#123;xxx&#125;,request:&#123;xxx&#125;,status:xxx,statusText:&#x27;xx&#x27;&#125;</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>参考文章<br><a target="_blank" rel="noopener" href="http://axios-js.com/zh-cn/docs/index.html">axios中文文档</a><br><a target="_blank" rel="noopener" href="http://www.lucklnk.com/godaddy/details/aid/195114672">axios拦截器实际应用场景</a><br><a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000008484070">fetch使用的常见问题及其解决办法</a><br><a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903599143649294">Jquery ajax, Axios, Fetch区别之我见</a></p>
</blockquote>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关博客</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
        <div class="popular-posts-date">2020-07-10</div>
      <div class="popular-posts-title"><a href="vue-cli4修改index-html中的title/" rel="bookmark">vue-cli4修改index.html中的title</a></div>
      
    </li>
    <li class="popular-posts-item">
        <div class="popular-posts-date">2020-05-22</div>
      <div class="popular-posts-title"><a href="React中的proxy/" rel="bookmark">React中的proxy</a></div>
      
    </li>
    <li class="popular-posts-item">
        <div class="popular-posts-date">2021-09-14</div>
      <div class="popular-posts-title"><a href="简易的把webpack配置分成两套，生产模式和开发模式/" rel="bookmark">简易的把webpack配置分成两套，生产模式和开发模式</a></div>
      
    </li>
    <li class="popular-posts-item">
        <div class="popular-posts-date">2020-05-28</div>
      <div class="popular-posts-title"><a href="React修改eslint配置/" rel="bookmark">React修改eslint配置</a></div>
      
    </li>
  </ul>


    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="wxb 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.png" alt="wxb 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="followme">
  <span>欢迎关注我的其它发布渠道</span>

  <div class="social-list">

      <div class="social-item">
        <a target="_blank" class="social-link" href="/atom.xml">
          <span class="icon">
            <i class="fa fa-rss"></i>
          </span>

          <span class="label">RSS</span>
        </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/Javescript/" rel="tag"># Javescript</a>
              <a href="/tags/HTML5/" rel="tag"># HTML5</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/React%20hooks%E4%B8%ADuseContext%E6%9B%B4%E6%96%B0%E6%95%B0%E6%8D%AE%E7%9A%84%E6%96%B9%E6%B3%95/" rel="prev" title="React hooks中useContext更新数据的方法">
                  <i class="fa fa-chevron-left"></i> React hooks中useContext更新数据的方法
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/H5%E5%8A%A8%E7%94%BB%E5%B8%A7requestAnimationFrame/" rel="next" title="H5动画帧requestAnimationFrame">
                  H5动画帧requestAnimationFrame <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wxb</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <!-- <span id="busuanzi_value_site_uv"></span> -->
        <span id="uv-views"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <!-- <span id="busuanzi_value_site_pv"></span> -->
        <span id="pv-views"></span>
      </span>
    </span>
</div><script src="/js/diy_footer.js"></script>
  <div class="powered-by">
    <div style="display: inline-flex;align-items: center;">
      <img src="/images/copyrihgt.png" alt="wxb 微信" with='20' height='20' style="margin-right: 4px;">
      <a href="https://beian.miit.gov.cn/" target="_blank">浙ICP备2022027687号</a>
    </div>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/medium-zoom/1.0.6/medium-zoom.min.js" integrity="sha256-EdPgYcPk/IIrw7FYeuJQexva49pVRZNmt3LculEr7zM=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.7.2/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"dearDreamWeb","repo":"blogwxb.github.io","client_id":"86685a6104f8e6ba5827","client_secret":"7cf015e84bbe755bde20c8aca767977e316304ad","admin_user":"dearDreamWeb","distraction_free_mode":true,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.7.2/gitalk.min.js","integrity":"sha256-Pmj85ojLaPOWwRtlMJwmezB/Qg8BzvJp5eTzvXaYAfA="},"path_md5":"6a596113acd718841f15cbd3c7e1b6a8"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>

</body>
</html>
